require('module-alias/register')
const createError = require('http-errors')
const express = require('express')
const path = require('path')
const cookieParser = require('cookie-parser')
const morgan = require('morgan')
const logger = require('./logger')

// 路由文件引用
const adminRoutes = require('./routes/adminRoutes.js')
const menuRoutes = require('./routes/menuRoutes.js')
const usersRoutes = require('./routes/userRoutes.js')
const uploadRoutes = require('./routes/uploadRoutes.js')
const memberLevelRoutes = require('./routes/memberLevelRoutes.js')
const articleRoutes = require('./routes/articleRoutes.js')
const goodsRoutes = require('./routes/goodsRoutes.js')
const goodsClassRoutes = require('./routes/goodsClassRoutes.js')

// Express 引用实例化
const app = express()

// 视图模板设置
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'jade')

// 使用 morgan 打印日志
app.use(morgan('dev'))
// 对 post 来的数据格式化
app.use(express.json())
// 对表单提交的数据格式化
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
    // 允许所有来源访问
    res.header('Access-Control-Allow-Origin', '*')
    // 允许访问的方式
    res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
    // 允许访问的请求头类型
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Authorization, Accept')
    res.header('Content-Type', 'application/json;charset=utf-8')
    // 处理 options 预请求
    req.method === 'OPTIONS' ? res.send(200) : next()
})

/**
 * 使用路由
 * */
app.use('/api/', adminRoutes)
app.use('/api/menu', menuRoutes)
app.use('/api/users', usersRoutes)
app.use('/api/upload', uploadRoutes)
app.use('/api/level', memberLevelRoutes)
app.use('/api/article', articleRoutes)
app.use('/api/goods', goodsRoutes)
app.use('/api/goodsClass', goodsClassRoutes)

// 拦截器
app.use((err, req, res) => {
    if (err.name === "UnauthorizedError") {
        res.status(401).send({ code: 401, msg: '无效的token' })
    }
})

app.use((req, res, next) => {
    next(createError(404))
})

// 错误处理
const _errorHandler = (err, req, res) => {
    logger.error(`${req.method} ${req.originalUrl}` + err.message)
    res.status(err.status || 500).json({
        code: -1,
        success: false,
        message: err.message,
        data: {}
    })
}
app.use(_errorHandler)

// 监听端口
const port = 8848
app.listen(port, () => {
    console.log('----------------------------')
    console.log('|  服务器已启动成功...     |')
    console.log(`|  http://127.0.0.1:${port}   |`)
    console.log('----------------------------')
})

module.exports = app
